package com.chmingx.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.chmingx.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CircleBreakerController {
    @Value("${service-url.nacos-user-service}")
    private String serviceUrl;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/payment/{id}")
    @SentinelResource(value = "consumer",
            blockHandler = "blockHandler", // 负责处理Sentinel控制台配置违规
            fallback = "fallbackHandler", // 负责处理java内部异常
            exceptionsToIgnore = {IllegalArgumentException.class} // 指定忽略的异常
    )
    public String getPaymentById(@PathVariable("id") Integer id) {
        if (id == 0) {
            // exceptionsToIgnore属性有IllegalArgumentException.class，
            //所以IllegalArgumentException不会跳入指定的兜底程序
            throw new IllegalArgumentException("非法参数异常");
        } else if (id == 1) {
            throw new NullPointerException("空指针异常");
        }
        return restTemplate.getForObject(serviceUrl + "/payment/" + id, String.class, id);
    }

    public String blockHandler(Integer id, BlockException blockException) {
        return "blockHandler-sentinel限流,无此流水: blockException" + blockException.getMessage();
    }

    public String fallbackHandler(Integer id, Throwable throwable) {
        return "兜底异常handlerFallback,exception内容  " + throwable.getMessage();
    }

    // ------ openfeign -----
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/consumer/openfeign/payment/{id}")
    public String getPaymentThroughFeign(@PathVariable("id") Integer id) {
        return paymentService.getPaymentById(id);
    }
}
